package vn.evolus.pencil.service.impl;

import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import vn.evolus.commons.data.DataAccessException;
import vn.evolus.commons.data.IRepository;
import vn.evolus.pencil.model.Role;
import vn.evolus.pencil.model.User;

public class PencilUserDetailsServiceImpl implements UserDetailsService {
	
	private IRepository repository;
	
	public PencilUserDetailsServiceImpl(IRepository repository) {
		super();
		this.repository = repository;
	}

	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = repository.getByKey(User.class, "username", username);
		if (user == null) throw new UsernameNotFoundException(username);
		
		
		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		
		for (Role role : user.getRoles()) {
			authorities.add(role);
		}
		
		org.springframework.security.core.userdetails.User userDetails = 
				new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), 
						user.isEnabled(), true, true, true, authorities);
		
		return userDetails;
	}

}
